package com.xiaobai.netease_news.services;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import com.xiaobai.netease_news.R;


public class TutorialMusicService extends Service
        implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {

    private MediaPlayer mediaPlayer;

    public TutorialMusicService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = MediaPlayer.create(this, R.raw.new_version);

        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);
    }

    @Override
    public void onDestroy() {
        mediaPlayer.release();
        stopSelf();

        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new Controller();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (mp != null) {
            mp.start();
        }
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (mp != null) {
            mp.reset();
            mp.start();
        }
        return true;
    }

    public class Controller extends Binder {
        public void start() {
            if (mediaPlayer != null) {
                mediaPlayer.start();
            }
        }

        public void pause() {
            if (mediaPlayer != null) {
                mediaPlayer.pause();
            }
        }

        public void stop() {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
            }
        }

        public void release() {
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
        }
    }
}
